﻿using System.Collections.ObjectModel;
using System.Reactive.Linq;
using Caliburn.Micro;
using Serialization;
using Wulong.Phone.Qiushi.Models;

namespace Wulong.Phone.Qiushi.ViewModels
{
    public class MainViewModelStorage : StorageHandler<MainViewModel>
    {
        public override void Configure()
        {
            AddInstruction().Configure(x =>
            {
                x.Key = "hotpics";

                x.Save = (instance, getKey, mode) => Observable.ToAsync<int>(n =>
                                                                                 {
                                                                                     var value = SilverlightSerializer.Serialize(instance._picstoryList);
                                                                                     x.StorageMechanism.Store(getKey(), value);
                                                                                 });
                x.Restore = (instance, getKey, mode) =>
                {
                    object value;
                    var key = getKey();

                    if (x.StorageMechanism.TryGet(key, out value))
                    {
                        Observable.ToAsync<int>(n =>
                                                    {
                                                        instance._picstoryList = (value == null)
                                                                                     ? null
                                                                                     : SilverlightSerializer.
                                                                                           Deserialize(
                                                                                               (byte[]) value) as
                                                                                       ObservableCollection<QiushiItem>;
                                                    });

                        //x.StorageMechanism.Delete(key);
                    }

                };
            }).InPhoneState().RestoreAfterViewReady();
        }
    }
}
